﻿using server.Model;
using System.Collections.Generic;
using log4net;
using server.Tool;
using MySql.Data.MySqlClient;
using server.Business;
using Utils;

namespace server.DAO
{
    /// <summary>
    /// 创建删除修改队
    /// </summary>
    public class EditGrounpDao : RoomDao
    {
        ILog Logger = log4net.LogManager.GetLogger("server.DAO.EditGrounpDao");

        private JoinRoomDao joinRoomDao = new JoinRoomDao();
        private ScoreDao scoreDao = new ScoreDao();
        private PublishPlayerState publishPlayerState = new PublishPlayerState();
        private KnapsackDao knapsackDao = new KnapsackDao();


        /// <summary>
        /// 更新房间
        /// </summary>
        /// <param name="session"></param>
        /// <param name="body"></param>
        /// <param name="room"></param>
        public void UpdateGrounp(PubgSession session, string body, string grounpId, string grounpName,
            string checkCode, string playerTime,string fireTime)
        {

            DataResult dataResult = new DataResult();
            Grounp p = SearchGrounpDao.GetGrounpById(grounpId);

            if (p != null && p.runState == 0)
            {
                dataResult.result = 1;
                dataResult.reason = "游戏运行中，无法修改游戏。";
                session.Send(GetSendData(dataResult, body));
                return;
            }
            //更新队
            string sql = "update grounp set name = '" + grounpName + "', playerTime = '" + playerTime + "', fireTime = '" + fireTime +
                "', checkCode = '" + checkCode + "', remainTime = '" + (int.Parse(playerTime)*60) + "' where id = @grounpId";
            MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

      
            //更新分队信息
            dataResult.result = 0;
            session.Send(GetSendData(dataResult, body));

        }


        /// <summary>
        /// 查询所有的队
        /// </summary>
        /// <returns></returns>
            private List<Grounp> GetAllRoom(int userId)
        {
            string sql = "select * from gronp where userId = @userId";
            List<Grounp> result = MySqlExecuteTools.GetObjectResult<Grounp>(sql, 
                new MySqlParameter[] { new MySqlParameter("@userId", userId) });
            return result;
        }

        /// <summary>
        /// 创建房间
        /// </summary>
        /// <param name="num">创建分队色数量</param>
        /// <param name="roomid">房间id</param>
        private void CreateRoom(int num,long roomid,string defaultCheckCode="123456")
        {
            for(int i=0;i<num;i++)
            {
               string  sql = "insert into room(grounpId,code,name,checkCode) " +
                   "values('" + roomid + "','" + (i+1) + "','" + "房间"+ (i+1) + "','" + defaultCheckCode + "')";
                MySqlExecuteTools.AddOrUpdate(sql);
            }
        }

        private  void DeleteRoom(string grounpId)
        {
            string sql = "select * from room where grounpId = @grounpId";
            List<Room> result = MySqlExecuteTools.GetObjectResult<Room>(sql,
                new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

            result.ForEach((item) => {

                int roomId = item.id;
                // 删除房间信息
                string deleteGronpSql = "delete  from room  where id = @roomId";
                MySqlExecuteTools.GetCountResult(deleteGronpSql, new MySqlParameter[] { new MySqlParameter("@roomId", roomId) });

                //删除房间和用户的关联表
                string delete_grounp_userSql = "delete  from  room_user  where room_id = @roomId";
                MySqlExecuteTools.GetCountResult(delete_grounp_userSql, new MySqlParameter[] { new MySqlParameter("@roomId", roomId) });
            });
        }
        private int minFenceRadius = 50;
        /// <summary>
        /// 更新范围
        /// </summary>
        /// <param name="frequency"></param>
        public void UpdateFenceScope(int frequency)
        {
            string sql = "select * from grounp where runState =0 and fenceLon>0 ORDER BY id DESC";
            List<Grounp> grounpList = MySqlExecuteTools.GetObjectResult<Grounp>(sql, null);

            for(int i=0;i< grounpList.Count;i++)
            {
                Grounp grounp = grounpList[i];
                bool checkLifeOver = CheckLifeOver(grounp.id);

                if(checkLifeOver)
                {
                    GameReset(grounp, true);
                }
                else
                {
                    float everyFrequencyCount = grounp.fenceTotalRadius / (grounp.playerTime * 60.00f / frequency);

                    //处理电子围栏的范围
                    if (grounp.remainTime > 0 && (grounp.remainTime - everyFrequencyCount) > 0)
                    {
                        float _fenceRadius = grounp.fenceRadius - everyFrequencyCount;
                        if (_fenceRadius < minFenceRadius)
                        {
                            _fenceRadius = minFenceRadius;
                        }
                        sql = "update  grounp set fenceRadius = '" + _fenceRadius +
                        "',remainTime='" + (grounp.remainTime - frequency) + "' where id = @grounpId;";
                        MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounp.id) });
                    }
                    else
                    {

                        GameReset(grounp, true);
                    }
                }
             
            }
     
            //joinRoomDao.GetAllRoom();

        }

        /// <summary>
        /// 检查所有的玩家是否命值为0，若为0，则结束游戏
        /// </summary>
        /// <param name="grounpId"></param>
        /// <returns></returns>
        private bool CheckLifeOver(int grounpId)
        {
            List<int>  userList = GetUserListByGrounp(grounpId);
            List<string> userListStr = new List<string>();
            userList.ForEach((item) => {

                userListStr.Add(item.ToString());
            });

            string result = StrUtil.ConnetString(userListStr, ",");
           string sql = "select * from life where userId in  (" + result + ") and lifeValue>0";
           int count =  MySqlExecuteTools.GetCountResult(sql, null);
            if(count==0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 复位游戏
        /// </summary>
        /// <param name="grounp"></param>
        /// <param name="isCreateLifeData">是否创建战绩表</param>
        private  void  GameReset(Grounp grounp,bool isCreateScoreData)
        {

            ResetGameData(grounp);
            //保存战绩,复位生命值
            scoreDao.SaveScoreResetLife(grounp.id, isCreateScoreData);

            //向管理员和玩家通知游戏结束
            //publishPlayerState.SendSingleUserMessage(grounp.userId, PublishPlayerState.Game_Over);
           // publishPlayerState.SendUserListByAdmin(grounp.userId, PublishPlayerState.Game_Over);

            //更新room和roomUser状态
            UpdateRoomAndUserState(grounp.id);

            //删除道具的相关数据
            knapsackDao.GameFinishDelete(grounp.id);
        }

        public void ResetGameData(Grounp grounp)
        {
            string sql = "update  grounp set fenceRadius = 2000,fenceTotalRadius=2000,playerTime=0," +
                  "runState = -1,fenceLon=-1,fenceLat=-1,remainTime='" + (grounp.playerTime * 60) + "' where id = @grounpId;";
            MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounp.id) });
        }

        public string StopGame(string grounpId)
        {
            Grounp grounp = MySqlExtendTools.GetEntityObjectByPrimaryKey<Grounp>(grounpId, "grounp");
            if(grounp==null)
            {
                return "-1";
            }
            else
            {
                GameReset(grounp, true);
                publishPlayerState.SendUserListByAdmin(grounp.userId, PublishPlayerState.Update_Command);

                return "0";
            }
        }

        public void DeleteKnapsack_info(int grounpId)
        {
           string sql =  "delete  from knapsack_info where game_id = " + grounpId;
           MySqlExecuteTools.AddOrUpdate(sql);

        }

        private void UpdateRoomAndUserState(int grounpId)
        {
            string sql = "select * from room where grounpId = @grounpId";
            List<Room> roomList = MySqlExecuteTools.GetObjectResult<Room>(sql,
                new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

            roomList.ForEach((room) => {

                //更新room状态
                sql = "update  room set runState = -1  where  id = " + room.id;
                MySqlExecuteTools.AddOrUpdate(sql);

                sql = "select * from room_user where room_id = @room_id";
                List<Room_User> roomUserList = MySqlExecuteTools.GetObjectResult<Room_User>(sql,
               new MySqlParameter[] { new MySqlParameter("@room_id", room.id) });
                roomUserList.ForEach((roomUser) => {

                    sql = "update  room_user set runState = -1  where  id = " + roomUser.id;
                    MySqlExecuteTools.AddOrUpdate(sql);
                });

            });

        }

        public string ClearAllRoomData(string grounpId)
        {

            string sql = "select * from room where grounpId = @grounpId";
            List<Room> roomList = MySqlExecuteTools.GetObjectResult<Room>(sql,
                new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

            LifeDao lifeDao = new LifeDao();
            roomList.ForEach((room) => {

                //更新room状态
                sql = "update  room set runState = -1  where  id = " + room.id;
                MySqlExecuteTools.AddOrUpdate(sql);

                sql = "select * from room_user where room_id = @room_id";
                List<Room_User> roomUserList = MySqlExecuteTools.GetObjectResult<Room_User>(sql,
                new MySqlParameter[] { new MySqlParameter("@room_id", room.id) });
                roomUserList.ForEach((roomUser) => {


                    int userid = roomUser.user_id;

                    lifeDao.ResetGlobCoin(userid);
                    //删除score
                    sql = "delete from score  where userId=" + userid;
                    MySqlExecuteTools.AddOrUpdate(sql);


                    sql = "delete from room_user  where id=" + roomUser.id;
                    MySqlExecuteTools.AddOrUpdate(sql);
                });

                sql = "delete from room  where id=" + room.id;
                MySqlExecuteTools.AddOrUpdate(sql);

            });


            return "0";
        }

    }
}
